;save/load game module
;saveload_buffer
;player_deck_status

;saveload_buffer structure
;		ARCOMAGE  R C  DS1	DS2       DS102  G1 G2  QCE
;		__ID____  _ _   _    _   ...    _	 _  _    _
;byte 
;offset	0	   7  8 9   10   11        111  112 113  114
;
; R   - random byte
; CRC - !(overflowed checksum) = !CRC  (! means cpl was applied)
; DS1 - first card status
; DSX - Xth card status
; G1 G2 - Gold bytes
; QCE - Quest Current Enemy

;saveload_buffer -> player_deck_status
;ret a=0 if everything went smooth, a=1 if crc error, a=2 if wrong id
buffer2deck_status:
	
	;firstly check block id
	ld		b,8	
	ld		hl,saveload_buffer
	ld		de,arcomage_id
buffer2deck_status_validate_id_loop:
	ld		c,[hl]
	ld		a,[de]
	cp		c
	jr		nz,buffer2deck_status_wrong_id
	inc		hl
	inc		de
	djnz	buffer2deck_status_validate_id_loop
	

	;second thing, let's validate crc
	ld		a,[saveload_buffer+8]					;random byte
	
	ld		hl,saveload_buffer+8+1+1
	ld		b,102
buffer2deck_status_crc_loop:
	add		a,[hl]
	inc		hl
	djnz	buffer2deck_status_crc_loop
	
	ld		b,a										;save calculated crc
	ld		a,[saveload_buffer+8+1+1+102]			;coins byte0
	add		b
	ld		b,a
	ld		a,[saveload_buffer+8+1+1+102+1]			;coins byte1
	add		b
	ld		b,a
	ld		a,[saveload_buffer+8+1+1+102+2]			;quest_current_enemy
	add		b	
	ld		b,a

	ld		a,[saveload_buffer+8+1]
	cpl												;!a

	cp		b
	jr		nz,buffer2deck_status_crc_error

	ld		hl,saveload_buffer+8+1+1
	ld		de,player_deck_status
	ld		bc,102
	ldir	
	
	ld		hl,saveload_buffer+8+1+1+102
	ld		a,[hl]
	ld		[shop_coins],a
	inc		hl
	ld		a,[hl]
	ld		[shop_coins+1],a
	inc		hl
	ld		a,[hl]
	ld		[quest_current_enemy],a
	
	xor		a
	ret

buffer2deck_status_crc_error:
	ld		a,1
	ret
buffer2deck_status_wrong_id:
	ld		a,2
	ret
	
	
	
;	
;player_deck_status -> saveload_buffer
;updates saveload_buffer
deck_status2buffer:
	;block ID
	ld		hl,arcomage_id							;"ARCOMAGE" is the block id for savegames
	ld		de,saveload_buffer
	ld		bc,8									;8 characters ;-)
	ldir
	
	ld		hl,saveload_buffer+8
	;generate a quick random number
	ld		a,r
	ld		[hl],a									;save random byte
	
	ld		b,102
	ld		hl,player_deck_status
deck_status2buffer_crc_loop:
	add		a,[hl]
	inc		hl
	djnz	deck_status2buffer_crc_loop	

	ld		b,a										;save crc on b
	ld		a,[shop_coins]
	add		b
	ld		b,a
	ld		a,[shop_coins+1]
	add		b
	ld		b,a
	ld		a,[quest_current_enemy]
	add		b	
													;a holds crc again
	cpl												;!a
	ld		hl,saveload_buffer+8+1
	ld		[hl],a									;save crc. Includes random byte, gold bytes and quest_current_enemy and all its bits are upside down (cpl). Source code of this game is available 
													;so doesn't make sense to make up a complex algorithm to avoid cheating savegames
	ld		hl,player_deck_status
	ld		de,saveload_buffer+8+1+1
	ld		bc,102
	ldir	
	
	ld		hl,saveload_buffer+8+1+1+102
	ld		a,[shop_coins]
	ld		[hl],a
	inc		hl
	ld		a,[shop_coins+1]
	ld		[hl],a
	inc		hl	
	ld		a,[quest_current_enemy]
	ld		[hl],a
	
	;buffer ready

	ret
